<?php
/**
 * Created by PhpStorm.
 * User: guokunsheng
 * Date: 2024/3/21
 * Time: 下午1:33
 */

namespace app\web\controller;

use app\webactive\service\LingqianAndBless;
use think\Controller;

/**
 * Class Pray
 * @package app\web\controller
 */
class Pray extends Controller
{
    // 准有好事官方服务号的配置
    protected $mp_appid = 'wx393a0263a86fd6f7';
    protected $mp_appsecret = '7774fc38a2b8e65da2bd155cf7c86177';

    public function index()
    {
        // 检查当前是否已登录，获取用户标识
        $this->checkLogin();
        // 读取当前登录的用户信息
        $sessionInfo = session('weixinlogin');
        if (!$sessionInfo || !is_array($sessionInfo))
        {
            return show(0, '登录失败');
        }
        $lingqianAndBlessService = new LingqianAndBless();
        $loginInfo = $lingqianAndBlessService->Login($sessionInfo);
        // 登录失败处理
        if (!$loginInfo['success'])
        {
            return show(0, $loginInfo['msg']);
        }
        // 今日祈福状态 [[type=>1, status=>0],[type=>2, status=>1],[type=>3, status=>0],]
        $data = $lingqianAndBlessService->getBlessHome($loginInfo['id']);

        return $this->fetch('', [
            'status1' => $data[0]['status'],
            'status2' => $data[1]['status'],
            'status3' => $data[2]['status'],
        ]);
    }

    public function api()
    {
        if ($this->request->isPost())
        {
            // 检查当前是否已登录，获取用户标识
            $this->checkLogin();
            // 读取当前登录的用户信息
            $sessionInfo = session('weixinlogin');
            if (!$sessionInfo || !is_array($sessionInfo))
            {
                return show(0, '登录失败');
            }
            $lingqianAndBlessService = new LingqianAndBless();
            $loginInfo = $lingqianAndBlessService->Login($sessionInfo);
            // 登录失败处理
            if (!$loginInfo['success'])
            {
                // 展示错误页面
                return show(0, $loginInfo['msg']);
            }
            $type = input('type/d', 0);
            // 1 =>财富 2=>爱情 3=>好事
            if (in_array($type, [1, 2, 3], true))
            {
                // 开始祈福
                $res = $lingqianAndBlessService->startBless($loginInfo['id'], $type);
                if ($res['success'])
                {
                    return show(200, '祈福成功');
                }
            }
        }
        return show(0, '祈福失败');
    }

    /**
     * 检查微信是否登录
     */
    protected function checkLogin()
    {
        if (empty(session('weixinlogin.unionid')))
        {
            // 跳转到微信登录
            $this->redirect('/web/pray/weixin_login');
        }
    }

    /**
     * 微信登陆
     * @doc https://developers.weixin.qq.com/doc/oplatform/Website_App/WeChat_Login/Wechat_Login.html
     */
    public function weixin_login(): void
    {
        // 考虑到可能会更换域名，此处读取当前请求的host
        if (strpos($_SERVER['HTTP_HOST'], 'goddessxzns') === false)
        {
            $appid = $this->mp_appid;
        } else
        {
            $appid = config('wechat.mp_appid');
        }
        $domain = 'https://' . $_SERVER['HTTP_HOST'];
        $redirect_uri = urlencode($domain . '/web/pray/weixin_back');
        header('location:https://open.weixin.qq.com/connect/oauth2/authorize?appid=' . $appid . '&redirect_uri=' . $redirect_uri . '&response_type=code&scope=snsapi_userinfo&state=' . md5(time()) . '#wechat_redirect');
        exit;
    }

    /**
     * 微信登陆返回
     */
    public function weixin_back(): void
    {
        // $wechatInfo = [
        //     'openid' => '',
        //     'unionid' => '',
        //     'headimgurl' => '',
        //     'nickname' => '',
        //     'sex' => '',
        // ];
        if (strpos($_SERVER['HTTP_HOST'], 'goddessxzns') === false)
        {
            $appid = $this->mp_appid;
            $appsecret = $this->mp_appsecret;
        } else
        {
            $wechat_conf = config('wechat');
            $appid = $wechat_conf['mp_appid'];
            $appsecret = $wechat_conf['mp_secret'];
        }
        $isEncode = input('is_encode/d', 0);

        $code = input('get.code/s');
        if (empty($code))
        {
            $this->error('微信授权失败！');
        }

        $token = urlencode(input('get.state/s'));
        if (empty($token))
        {
            $this->error('获取token失败！');
        }
        $access_token = session('weixinlogin.access_token');
        if (empty($access_token) || $access_token === '')
        {
            $access_token_url = 'https://api.weixin.qq.com/sns/oauth2/access_token?appid=' . $appid . '&secret=' . $appsecret . '&code=' . $code . '&grant_type=authorization_code';
            $access_token = json_decode(file_get_contents($access_token_url), false);
            if (isset($access_token->errcode))
            {
                $this->error('授权失败');
            }
            session('weixinlogin.access_token', $access_token->access_token);
            session('weixinlogin.refresh_token', $access_token->refresh_token);
            session('weixinlogin.openid', $access_token->openid);
        }

        $user_info_url = 'https://api.weixin.qq.com/sns/userinfo?access_token=' . session('weixinlogin.access_token') . '&openid=' . session('weixinlogin.openid') . '&lang=zh_CN';
        $user_info = json_decode(file_get_contents($user_info_url), false);
        if (isset($user_info->errcode))
        {
            $access_token_url = 'https://api.weixin.qq.com/sns/oauth2/refresh_token?appid=' . $appid . '&grant_type=refresh_token&refresh_token=' . session('weixinlogin.refresh_token');
            $access_token = json_decode(file_get_contents($access_token_url), true);
            if (isset($access_token['access_token'], $access_token['refresh_token'], $access_token['openid']) && !empty($access_token))
            {
                session('weixinlogin.access_token', $access_token['access_token']);
                session('weixinlogin.refresh_token', $access_token['refresh_token']);
                session('weixinlogin.openid', $access_token['openid']);

                $user_info_url = 'https://api.weixin.qq.com/sns/userinfo?access_token=' . $access_token['access_token'] . '&openid=' . $access_token['openid'] . '&lang=zh_CN';
                $user_info = json_decode(file_get_contents($user_info_url), false);
                if (isset($user_info->errcode))
                {
                    echo '<h1>错误：</h1>' . $user_info->errcode;
                    echo '<br/><h2>错误信息：</h2>' . $user_info->errmsg;
                    exit;
                }
            } else
            {//失败的话，重新授权登录
                if (40001 === $user_info->errcode)
                {//40001为invalid credential, access_token is invalid or not latest, hints: [ req_id: EfKfY24ce-3ItL5 ]，清空access_token
                    session('weixinlogin.access_token', null);
                }
                $this->redirect('/web/pray/weixin_login');
            }
        }
        //把unionid、headimgurl、name 保存到session里
        session('weixinlogin.unionid', $user_info->unionid);
        session('weixinlogin.headimgurl', $user_info->headimgurl);
        session('weixinlogin.name', $user_info->nickname);
        session('weixinlogin.sex', $user_info->sex);

        $this->redirect('/web/pray/index');
    }
}
